<template>
  <div class="anniversary-edit-view">
    <AppHeader title="编辑纪念日">
      <template #left>
        <el-button circle @click="router.back()">
          <el-icon><ArrowLeft /></el-icon>
        </el-button>
      </template>
    </AppHeader>

    <div class="edit-form-container">
      <el-form v-if="editedAnniversary" :model="editedAnniversary" label-width="100px">
        <el-form-item label="标题">
          <el-input v-model="editedAnniversary.title"></el-input>
        </el-form-item>
        <el-form-item label="目标日期">
          <el-date-picker 
            v-model="editedAnniversary.targetDate" 
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="editedAnniversary.description"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveChanges">保存</el-button>
          <el-button @click="cancelEdit">取消</el-button>
        </el-form-item>
      </el-form>
      <div v-else>
        <p>加载中或纪念日不存在...</p>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import dayjs from 'dayjs' // Import dayjs for date handling
import AppHeader from '../components/AppHeader.vue'
import { ArrowLeft } from '@element-plus/icons-vue'

export default {
  name: 'AnniversaryEditView',
  components: {
    AppHeader,
    ArrowLeft,
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const editedAnniversary = ref(null)

    const fetchAnniversary = async (id) => {
      try {
        const response = await axios.get(`http://localhost:8080/anniversary/query`, {
          params: { id: id }
        })
        // Assuming the anniversary data is directly in response.data
        if (response.data && Object.keys(response.data).length > 0) {
          // Format targetDate to ensure compatibility with el-date-picker if needed
          if (response.data.targetDate && !dayjs(response.data.targetDate).isValid()) {
              console.warn('Invalid targetDate format received:', response.data.targetDate);
              // Optionally handle invalid date format, e.g., set to null or a default
              response.data.targetDate = null;
          }
          editedAnniversary.value = response.data
        } else {
          console.error('Anniversary not found or empty data for id:', id);
          editedAnniversary.value = null; // Indicate not found
        }
      } catch (error) {
        console.error('Error fetching anniversary for editing:', error)
        editedAnniversary.value = null; // Indicate error
      }
    }

    const saveChanges = async () => {
      if (!editedAnniversary.value) return

      try {
        // Assuming the update API is PUT /anniversary/update with body
        const response = await axios.put('http://localhost:8080/anniversary/update', editedAnniversary.value)
        
        // Assuming a successful update returns code 0 or a specific status
        if (response.data && response.data.code === 0) { // Adjust condition based on your API success response
          console.log('纪念日更新成功')
          // Navigate back to the anniversary list or detail page
          router.push({ name: 'Anniversary' })
        } else if (response.status === 200) { // Fallback check for HTTP 200 if API doesn't use a code field
             console.log('纪念日更新成功 (HTTP 200)')
             router.push({ name: 'Anniversary' })
        } 
        else {
           console.error('纪念日更新失败:', response.data);
           alert('保存失败，请稍后再试。');
        }
      } catch (error) {
        console.error('保存纪念日出错:', error)
        alert('保存出错，请稍后再试。');
      }
    }

    const cancelEdit = () => {
      // Navigate back without saving
      router.push({ name: 'Anniversary' })
    }

    onMounted(() => {
      const anniversaryId = route.params.id
      if (anniversaryId) {
        fetchAnniversary(anniversaryId)
      }
    })

    return {
      editedAnniversary,
      saveChanges,
      cancelEdit,
      router
    }
  }
}
</script>

<style scoped>
.anniversary-edit-view {
  padding-top: 60px; /* Add padding for fixed header */
  padding: 20px; /* Add general padding */
}

.edit-form-container {
  max-width: 600px; /* Limit form width */
  margin: 20px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* Adjustments for Element Plus components within the form if needed */
.edit-form-container .el-form-item {
  margin-bottom: 20px;
}
</style> 